import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/ai_character.dart';

class CharacterController extends ChangeNotifier {
  List<AICharacter> _characters = [];
  List<AICharacter> get characters => _characters;

  Future<void> initializeCharacters() async {
    final prefs = await SharedPreferences.getInstance();
    final charactersJson = prefs.getString('characters');
    if (charactersJson != null) {
      final List<dynamic> decoded = const JsonDecoder().convert(charactersJson);
      _characters = decoded.map((json) => AICharacter.fromJson(json)).toList();
    } else {
      _characters = _getDefaultCharacters();
      await saveCharacters();
    }
    notifyListeners();
  }

  List<AICharacter> _getDefaultCharacters() {
    return [
      AICharacter(
        id: 'zeus',
        name: 'Zeus',
        description: 'The king of the gods, ruler of Mount Olympus.',
        avatarUrl: 'assets/images/zeus.png',
        unlockPrice: 0,
        isUnlocked: true,
        personality: 'Powerful and authoritative',
        topics: ['Leadership', 'Power', 'Justice'],
      ),
      AICharacter(
        id: 'athena',
        name: 'Athena',
        description: 'Goddess of wisdom, war, and crafts.',
        avatarUrl: 'assets/images/athena.png',
        unlockPrice: 100,
        personality: 'Wise and strategic',
        topics: ['Wisdom', 'Strategy', 'Arts'],
      ),
      AICharacter(
        id: 'apollo',
        name: 'Apollo',
        description: 'God of music, poetry, art, and medicine.',
        avatarUrl: 'assets/images/apollo.png',
        unlockPrice: 150,
        personality: 'Creative and healing',
        topics: ['Arts', 'Medicine', 'Music'],
      ),
    ];
  }

  Future<void> saveCharacters() async {
    final prefs = await SharedPreferences.getInstance();
    final charactersJson = const JsonEncoder().convert(
      _characters.map((c) => c.toJson()).toList(),
    );
    await prefs.setString('characters', charactersJson);
  }

  Future<void> unlockCharacter(String characterId) async {
    final index = _characters.indexWhere((c) => c.id == characterId);
    if (index != -1) {
      _characters[index] = _characters[index].copyWith(isUnlocked: true);
      await saveCharacters();
      notifyListeners();
    }
  }

  AICharacter? getCharacterById(String id) {
    try {
      return _characters.firstWhere((character) => character.id == id);
    } catch (e) {
      return null;
    }
  }
} 